package cn.bitkit.assist.code.creator;

import cn.bitkit.assist.code.BaseCreator;
import cn.bitkit.assist.code.vo.CodeVO;
import cn.bitkit.assist.code.vo.FieldVO;
import cn.bitkit.assist.constants.ClassMybatisEnum;
import cn.bitkit.assist.constants.MybatisColumnEnum;
import cn.bitkit.base.exception.BusinessAssert;
import cn.bitkit.base.util.PathUtil;
import cn.bitkit.tools.file.TextHelper;

import java.util.stream.Collectors;

public class SqlCreator extends BaseCreator {

    @Override
    public void create() {
        final String template = getTemplate("sql.tpl");
        TextHelper builder = TextHelper.loadString(template);
        if(projectVO.getDatabaseName() == null){
            builder.setValue("databaseName", "");
        }else {
            builder.setValue("databaseName", projectVO.getDatabaseName()+".");
        }
        builder.setValue("tableName", entityVO.getTableName());
        builder.setValue("columnList", getColumnList());
        builder.setValue("primaryKey", codeVO.getPrimaryKey());
        builder.setValue("tableComment", entityVO.getEntityComment());
        String text = builder.getText();
        String filePath = PathUtil.asPath(projectVO.getAbsoluteSqlFolder()) + entityVO.getTableName() + ".sql";
        writeText(text, filePath);

    }

    private String getColumnList() {
        final String template = "`${column}` ${columnType}${constraint} COMMENT '${comment}',";
        return entityVO.getFieldList().stream().map(e -> {
            TextHelper builder = TextHelper.loadString(template);
            builder.setValue("column", e.getColumn());
            builder.setValue("comment", e.getName());
            builder.setValue("columnType", getColumnType(e, codeVO));
            String constraint = e.getId() ? " NOT NULL" : "";
            builder.setValue("constraint", constraint);
            return builder.getText();
        }).collect(Collectors.joining("\r\n"));
    }

    private String getColumnType(FieldVO vo, CodeVO codeVO){
        ClassMybatisEnum mybatisEnum = ClassMybatisEnum.getMybatisType(vo.getFieldClass());
        BusinessAssert.isNotNull(mybatisEnum, "mybatis type not found:"+vo.getField());
        MybatisColumnEnum columnEnum = MybatisColumnEnum.getColumnType(mybatisEnum.mybatisType, projectVO.getDialectType());
        BusinessAssert.isNotNull(columnEnum, "column type not found:"+vo.getField()+"-"+projectVO.getDialectType());
        String columnType = columnEnum.columnType;
        if(columnEnum.length != null && columnEnum.scale == null){
            columnType = columnType + "(" + columnEnum.length + ")";
        }
        if(columnEnum.length != null && columnEnum.scale != null){
            columnType = columnType + "(" + columnEnum.length + "," + columnEnum.scale + ")";
        }
        return columnType;
    }
}
